<template>
    <div class='cart-container'>
        <div class="cc-caontainer">
            <div class="cc-c-head">
                <div class="cart-tip">
                    <span>购物车管理</span>
                </div>
                <div class="cart-search">
                    <el-input placeholder="请输入购物车信息" v-model="searchInfo">
                        <el-button @click="searchCart()" class="test" slot='append' icon="el-icon-search"></el-button>
                    </el-input>
                </div>
                <div class="settle">
                    <div class="end-price">
                        <span class="end-procetip">已选择商品</span>
                        <span class="all-price">￥{{ allPrice }} {{ !checkSettle ? '.00' : '' }}</span>
                    </div>
                    <div :class="checkSettle ? 'checkSettle end-settle' : 'end-settle'"
                        @click="checkSettle ? settle() : ''">结算
                    </div>
                </div>
            </div>
            <div class="cc-c-body">
                <div v-if="cartLen > 0">
                    <el-checkbox class="all-in" :isIndeterminate="isIndeterminate" v-model="checkAll"
                        @change="handleCheckAllChange">全选</el-checkbox>
                    <span style="color: #ff4000; font-size: 12px; font-weight: 700;">
                        已选商品 ({{ checkCatrs.length }})
                    </span>
                </div>
                <div v-if="cartList.length > 0">
                    <el-checkbox-group v-model="checkCatrs" @change="handleCheckedCitiesChange">
                        <div class="mc-pm-box" v-for="cart in cartList" :key="cart.cart.id">
                            <div class="pre-container">
                                <!-- 选中框 -->
                                <div class="check-item">
                                    <el-checkbox class="c-i-item" :key="cart.cart.id" :label="cart.cart.id" :title="cart.cart.spuTitle">
                                        {{ cart.cart.spuTitle }}
                                    </el-checkbox>
                                </div>

                                <!-- 商品图片 -->
                                <div class="product-img">
                                    <img :src="cart.cart.spuImg" alt="product image"
                                        @click="productDetail(cart.cart.spuId, cart.sale)">
                                </div>

                                <!-- 商品描述 -->
                                <div class="product-detail mid-container">
                                    <span v-html="cart.cart.spuDetail"
                                        @click="productDetail(cart.cart.spuId, cart.sale)"></span>
                                </div>

                                <!-- 价格显示 -->
                                <div class="price-container">
                                    <span :title="cart.cart.spuPrice + '元人名币'">{{ cart.cart.spuPrice }}￥</span>
                                </div>

                                <!-- 尾部 -->
                                <div class="tail-container">
                                    <div>当前商品状态 :
                                        <span style="color: #ff4000; font-weight: 800;">
                                            {{ checkProductStatus(cart.sale) }}
                                        </span>
                                    </div>

                                    <ul>
                                        <li>
                                            <span @click="collect(cart.cart)">移入收藏夹</span>
                                        </li>
                                        |
                                        <li>
                                            <span @click="delteeCart(cart.cart.id)">删除</span>
                                        </li>
                                    </ul>
                                </div>
                            </div>
                        </div>
                    </el-checkbox-group>
                </div>
                <!-- <div v-if="cartList.length == 0">
                    <el-empty :image-size="400"></el-empty>
                </div> -->

                <!-- 结算 -->
                <div>
                    <!-- 结算 -->
                </div>

            </div>
        </div>
    </div>
</template>
<script>

const cartOptions = [];

export default {
    name: 'cart',
    data() {
        return {
            checkAll: false,   // 是否选中全部
            checkCatrs: [],    // 默认选中的，选中的
            carts: cartOptions,    //  全选中的情况下
            isIndeterminate: false,  // 控制全部选中的样式

            memberVo: [],
            cartList: [],
            searchInfo: '',
            allPrice: 0.00,
            checkSettle: false,

            cartLen: 0,


        };
    },
    components: {
    },
    methods: {

        /**
        * 收藏商品
        */
        collect(product) {
            let collectVo = {}
            collectVo.memberId = this.memberVo.id
            collectVo.spuId = product.spuId
            collectVo.spuImg = product.spuImg
            collectVo.spuName = product.spuTitle
            collectVo.price = product.spuPrice
            this.$http({
                url: this.$http.adornUrl("/shitou-member/shitoumember/membercollectspu/createCollect"),
                method: 'post',
                data: this.$http.adornData(collectVo)
            }).then(({ data }) => {
                if (data.code == 200) {
                    this.$message({
                        type: 'success',
                        message: '收藏商品成功'
                    })
                } else if (data.code == 402) {
                    this.$router.push({ path: '/member/login' })
                } else {
                    this.$message({
                        type: 'warning',
                        message: data.message
                    })
                }
            })
        },


        /**
        * 选中全部
        * @param {*} val 判断是否全选的依据
        */
        handleCheckAllChange(val) {
            this.checkCatrs = val ? cartOptions : [];
            this.isIndeterminate = false;
            this.allPrice = this.countPrice(this.checkCatrs)
        },


        /**
         * 选中单个时，判断是否已经全部选中
         * @param {*} value 当前chebox节点的值
         */
        handleCheckedCitiesChange(value) {
            let checkedCount = value.length;
            this.checkAll = checkedCount === this.carts.length;
            this.isIndeterminate = checkedCount > 0 && checkedCount < this.carts.length;
            this.allPrice = this.countPrice(value)
        },


        /**
         * 计算商品总价格
         */
        countPrice(spuIds) {
            let tempPrice = 0;
            this.cartList.forEach((item) => {
                let cart = item.cart;
                let len = spuIds.length;
                for (let i = 0; i < len; i++) {
                    if (spuIds[i] == cart.id) {
                        tempPrice += cart.spuPrice
                    }
                }
            })
            this.checkSettle = tempPrice == 0 ? false : true;
            return tempPrice;
        },


        /**
         * 获得当前用户购物车信息
         */
        getMemberCart() {
            this.$http({
                url: this.$http.adornUrl(`/shitou-cart/shitoucart/cart/getMemberCart/${this.memberVo.id}`),
                method: 'post'
            }).then(({ data }) => {
                if (data.code == 200 ) {
                    this.cartList = data.data==null?[]:data.data
                    this.cartLen = this.cartList.length
                } else {
                    this.$message({
                        type: 'warning',
                        message: data.message
                    })
                }
                this.initOption()
            })
        },


        /**
         * 初始化cartOption,选中的菜单
         */
        initOption() {
            this.cartList.forEach((cart) => {
                cartOptions.push(
                    cart.cart.id
                )
            })
        },


        /**
         * 检查商品是否可购买
         * @param {*} sale 是否可购买
         */
        checkProductStatus(sale) {
            if (sale == 1) {
                return "可购买"
            } else if (sale == 2) {
                return "已售罄"
            } else if (sale == 3) {
                return "商品已下架"
            }else {
                return "商品异常"
            }
        },


        /**
         * 商品id，前往商品详情页面
         * @param {*} spuId
         * @param {*} sale
         */
        productDetail(spuId, sale) {
            if (sale != 1) {
                this.$message({
                    type: 'warning',
                    message: '商品已下架或售罄'
                })
                return;
            }
            this.$router.push({
                path: '/product/productDetail',
                query: { spuId: spuId }
            })
        },

        /**
         * 结算
         */
        settle() {

            // 组装spuIds
            let spuIds = []
            this.cartList.forEach((cart) => {
                this.checkCatrs.forEach((cartId) => {
                    if (cart.cart.id == cartId) {
                        spuIds.push(cart.cart.spuId)
                    }
                })
            })
            // 页面跳转，数据传输
            this.$router.push({
                path: '/order/buyproduct',
                query: {
                    spuIds: spuIds
                }
            })

        },

        /**
         * 删除购物车
         * @param {*} cartId
         */
        delteeCart(cartId) {
            this.$http({
                url: this.$http.adornUrl(`/shitou-cart/shitoucart/cart/removeMemberCart?cartId=${cartId}&memberId=${this.memberVo.id}`),
                method: 'post'
            }).then(({ data }) => {
                if (data.code == 200) {
                    this.$message({
                        type: 'success',
                        message: '删除购物车成功'
                    })
                    if (this.cartList.length == 1) {
                        this.$router.go(0)
                        return;
                    }
                    this.getMemberCart()
                } else {
                    this.$message({
                        type: 'warning',
                        message: data.message
                    })
                }
            })
        },


        /**
         * 搜索购物车
         */
        searchCart() {
            this.$http({
                url: this.$http.adornUrl(`/shitou-cart/shitoucart/cart/searchCart?searchInfo=${this.searchInfo}&memberId=${this.memberVo.id}`),
                method: 'post'
            }).then(({ data }) => {
                if (data.code == 200) {
                    if (data.data != undefined && data.data.length > 0) {
                        this.cartList = data.data;
                    } else if (data.data == undefined) {
                        this.$message({
                            type: 'success',
                            message: '没有该商品'
                        })
                        this.getMemberCart()
                    }
                } else {
                    this.$message({
                        type: 'warning',
                        message: data.message
                    })
                }
            })
        }


    },
    async created() {
        let member = await this.$memberInfo()
        if (member !== null) {
            this.memberVo = member;
            this.getMemberCart();
        }
    }

}
</script>
<style scoped>
@import url("../../utils/css/cart.css");
@import url("../../utils/css/manageproduct.css");
</style>
